import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.ImageIcon;

/*
 * This class represents the simulation engine
 */

public class Engine {
		
	//constructor
	public void Engine(){
		
	}
	
	//this function runs the simulation engine
	public void run(){
		/*simulation settings*/
		int thresholdCount=SplitSim.splitCount;
		int tBias=SplitSim.truncationBias;
		int hitMark=SplitSim.thresholdHits;
		double lastLimit;
		
		SplitSimSystem sNew = new SplitSimSystem();
		HashMap<String,Double> startState = new HashMap<String,Double>();
		startState = sNew.getState();
		sNew.initialize(0,0,startState);
		double maxThreshold=sNew.getMaxPar();
		double startThreshold=sNew.getStartPar();
		double thresholdJump = (maxThreshold-startThreshold)/thresholdCount;
		
		SplitSim.thresholds.add(new Threshold(0,startThreshold,startThreshold));
		SplitSim.thresholds.get(0).addState(sNew.getState());
		System.out.println(startThreshold+thresholdJump);
		System.out.println(startThreshold);
		
		java.net.URL statusURL = this.getClass().getResource("status.gif");
		ImageIcon statusIcon = new ImageIcon(statusURL);
		SplitSim.statusIcon = statusIcon;
		
		
		for (int level=1;level<=thresholdCount;level++){
			
			SplitSim.startSimulation();
			lastLimit = (SplitSim.thresholds.get(level-1)).getUpperLimit();
			double upperLimit = lastLimit + thresholdJump;
			double lowerLimit = lastLimit - tBias*thresholdJump;
			
			System.out.println(upperLimit+"--"+lowerLimit);
			
			
			if ( lowerLimit<startThreshold){
				lowerLimit=startThreshold;
			}
			SplitSim.thresholds.add(new Threshold(level,upperLimit,lowerLimit));

			while (SplitSim.thresholds.get(level).getHitCount() < hitMark){
				SplitSimSystem s = new SplitSimSystem();
				//System.out.println("Choosing temp of "+SplitSim.thresholds.get(level-1).getRandomState()+" at level "+level);
				s.initialize(upperLimit,lowerLimit,SplitSim.thresholds.get(level-1).getRandomState());
				if (s.run()){
					SplitSim.thresholds.get(level).addHitCount();
					SplitSim.thresholds.get(level).addState(s.getState());
				}
				else{
					SplitSim.thresholds.get(level).addMissCount();
				}
			}
			//System.out.println("HitRatio: "+SplitSim.thresholds.get(level).getHitRatio());
			if (level==thresholdCount)
				SplitSim.endSimulation();
		}
	}

}
